package com.hsytech.dijiebao.person;

import java.io.File;
import java.io.FileNotFoundException;

import org.json.JSONObject;

import com.hsytech.dijiebao.MainActivity;
import com.hsytech.dijiebao.R;
import com.hsytech.dijiebao.base.BaseApplication;
import com.hsytech.dijiebao.base.BaseFragment;
import com.hsytech.dijiebao.person.activity.ChangePasswordActivity;
import com.hsytech.dijiebao.person.activity.CollectActivity;
import com.hsytech.dijiebao.person.activity.InformitionActivity;
import com.hsytech.dijiebao.person.activity.ReleaseActivity;
import com.hsytech.dijiebao.person.activity.SeeCityActivity;
import com.hsytech.dijiebao.person.dao.InformationDao;
import com.hsytech.dijiebao.utils.Constants;
import com.hsytech.dijiebao.utils.FileUtils;
import com.hsytech.dijiebao.utils.SharedPreferencesTools;
import com.hsytech.dijiebao.view.CircleImageView;
import com.squareup.picasso.Picasso;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class Fragment03 extends BaseFragment {
    private View root;
    private ImageButton top_back_btn;
    private TextView bar_title_tv, user_name;
    private RelativeLayout relativeLayout_city, seeCity, back_activity, my_release, collect_my, os_informition,
            password, delete_center;
    private CircleImageView activity_four_myRelease0;
    private File mTmpFile, postFile;
    final String start = Environment.getExternalStorageState();
    private TextView new_city, finish_nick_name;
    private PopupWindow pop2, pop1;
    private String head_photo;
    private EditText nick_name;
    private Uri commonUri, afterCropUri;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        root = inflater.inflate(R.layout.fragment_person_main, container, false);
        initView();
        getHttp();
        return root;
    }

    private void initTitle() {
        delete_center = (RelativeLayout) root.findViewById(R.id.delete_center);
        delete_center.setVisibility(View.GONE);
        bar_title_tv = (TextView) root.findViewById(R.id.bar_title_tv);
        bar_title_tv.setText("我的");
    }

    private void initBody() {
        user_name = (TextView) root.findViewById(R.id.user_name);
        user_name.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                LayoutInflater localinflater = (LayoutInflater) getActivity().getSystemService

                        (Context.LAYOUT_INFLATER_SERVICE);
                View view = localinflater.inflate(R.layout.nick_name, null);

                // View
                // view=commnInflater.inflate(R.layout.activity_worker_user_item,(ViewGroup)
                // root, false);
                pop1 = new PopupWindow(getActivity());

                showNickPopupWindow(pop1, root, view);
                nick_name = (EditText) view.findViewById(R.id.nick_name);
                finish_nick_name = (TextView) view.findViewById(R.id.finish_nick_name);
                finish_nick_name.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        postHttp();

                    }
                });

            }
        });

        seeCity = (RelativeLayout) root.findViewById(R.id.seeCity);
        seeCity.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent(getActivity(), SeeCityActivity.class);
                startActivity(intent);
            }
        });
        // 系统消息

        os_informition = (RelativeLayout) root.findViewById(R.id.os_informition);
        os_informition.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                Intent intent = new Intent(getActivity(), InformitionActivity.class);
                startActivity(intent);
            }
        });
        // 退出系统
        back_activity = (RelativeLayout) root.findViewById(R.id.back_activity);
        back_activity.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // SystemManager.exit();
                SharedPreferencesTools.writeToken(getActivity(), "");
                SharedPreferencesTools.writeCityID(getActivity(), "");
                SharedPreferencesTools.writeCityName(getActivity(), "");
                SharedPreferencesTools.writeUid(getActivity(), "");
                InformationDao.informationDao.resetTable();
                ((MainActivity) getActivity()).startActivityWithTaskCleared(MainActivity.class);

            }
        });

        // 我的发布
        my_release = (RelativeLayout) root.findViewById(R.id.my_release);
        my_release.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent(getActivity(), ReleaseActivity.class);
                startActivity(intent);
            }
        });

        // 我的收藏
        collect_my = (RelativeLayout) root.findViewById(R.id.collect_my);
        collect_my.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent(getActivity(), CollectActivity.class);
                startActivity(intent);
            }
        });
        // 修改密码
        password = (RelativeLayout) root.findViewById(R.id.password);
        password.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent(getActivity(), ChangePasswordActivity.class);
                startActivity(intent);
            }
        });

        activity_four_myRelease0 = (CircleImageView) root.findViewById(R.id.activity_four_myRelease0);

        activity_four_myRelease0.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Context context = getActivity();
                LayoutInflater localinflater = (LayoutInflater) context.getSystemService

                        (Context.LAYOUT_INFLATER_SERVICE);
                View view = localinflater.inflate(R.layout.activity_worker_user_item, null);
                view.getBackground().setAlpha(00);
                pop2 = new PopupWindow(getActivity());

                showPopupWindow(pop2, root, view);
                RelativeLayout parent = (RelativeLayout) view.findViewById(R.id.parent);
                parent.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        if (pop2.isShowing()) {

                            pop2.dismiss();
                        }
                    }
                });
                Button item_popupwindows_camera = (Button) view.findViewById(R.id.item_popupwindows_camera);
                item_popupwindows_camera.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        openCamera();
                        if (pop2.isShowing()) {

                            pop2.dismiss();

                        }
                    }
                });
                Button item_popupwindows_Photo = (Button) view.findViewById(R.id.item_popupwindows_Photo);
                item_popupwindows_Photo.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        openPhoto();
                        if (pop2.isShowing()) {

                            pop2.dismiss();

                        }
                    }
                });

            }
        });

    }

    // 获取fragment03数据
    private void getHttp() {
        // 传参
//		RequestParams data = new RequestParams();
//		if (SharedPreferencesTools.getTOKEN(getActivity()) == null) {
//			// Toast.makeText(getActivity(), "请先登陆", Toast.LENGTH_SHORT).show();
//			showToast("请先登陆");
//		} else {
//
//			data.put("token", SharedPreferencesTools.getTOKEN(getActivity()));
//		}
//		HttpUtils.get(Constants.HTTP_MYF, data, new JsonResponseHandler() {
//			@Override
//			public void onSuccess(JSONObject data) {
//				JSONObject result = data.optJSONObject("result");
//				String id = result.optString("id");
//				String head_photo1 = result.optString("head_photo");
//
//				String djb_num = result.optString("djb_num");
//				String token = result.optString("token");
//				String name = result.optString("name");
//				Picasso.with(getActivity()).load("http://djb.dev.hsydev.com/Upload/image_sm/" + head_photo1)
//						.into(activity_four_myRelease0);
//				user_name.setText(name);
//			}
//
//			@Override
//			public void onFailure(int statusCode, Throwable throwable) {
//				// TODO Auto-generated method stub
//				super.onFailure(statusCode, throwable);
//			}
//
//		});
    }

    // 上传图片
    private void postImage() {
//		RequestParams data = new RequestParams();
//		BaseApplication.MyDialog.show(getActivity());
//		try {
//			Log.d("图片", "上传图片uri:" + commonUri);
//			Log.d("图片", "上传图片path:" + commonUri.getPath());
//			Log.d("图片", "上传图片file:" + new File(commonUri.getPath()));
//			data.put("1235", postFile);
//		} catch (FileNotFoundException e) {
//			e.printStackTrace();
//		}
//		HttpUtils.post(Constants.HTTP_POST_IMAGE, data, new JsonResponseHandler() {
//			@Override
//			public void onSuccess(JSONObject data) {
//				head_photo = data.optString("result");
//
//				postHead();
//
//			}
//
//			@Override
//			public void onError(String mess) {
//				// TODO Auto-generated method stub
//				super.onError(mess);
//
//				showToast(mess);
//			}
//
//		});
    }

    // 上传/修改图片
    private void postHead() {
//		RequestParams data = new RequestParams();
//		if (SharedPreferencesTools.getTOKEN(getActivity()) == null) {
//			showToast("请先登陆");
//		} else {
//
//			data.put("token", SharedPreferencesTools.getTOKEN(getActivity()));
//		}
//		data.put("head_photo", head_photo);
//		HttpUtils.post(Constants.HTTP_POST_HEAD, getActivity(), data, new JsonResponseHandler() {
//			@Override
//			public void onSuccess(JSONObject data) {
//				String result = data.optString("result");
//				BaseApplication.MyDialog.dismiss();
//				showToast("上传成功");
//				Picasso.with(getActivity()).load(postFile).fit().into(activity_four_myRelease0);
//			}
//
//			@Override
//			public void onError(String mess) {
//				super.onError(mess);
//				Toast.makeText(getActivity(), mess, Toast.LENGTH_SHORT).show();
//			}
//
//		});
    }

    // 打开相册
    private void openPhoto() {
        Log.d("图片", "打开相册");
        // Intent picture = new Intent(Intent.ACTION_PICK,
        // android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        Intent picture = new Intent(Intent.ACTION_GET_CONTENT);
        picture.setType("image/*");
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {// 4.4及以上
            picture.setAction(Intent.ACTION_OPEN_DOCUMENT);
        } else {// 4.4以下
            picture.setAction(Intent.ACTION_GET_CONTENT);
        }

        startActivityForResult(picture, Constants.MY_OPEN_PHOTO);
    }

    // 打开相机
    private void openCamera() {
        Log.d("图片", "打开相机");
        Intent cameraIntent = new Intent();
        cameraIntent.setAction("android.media.action.IMAGE_CAPTURE");
        cameraIntent.addCategory("android.intent.category.DEFAULT");
        mTmpFile = FileUtils.createTmpFile(getActivity());
        commonUri = Uri.fromFile(mTmpFile);
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, commonUri);
        startActivityForResult(cameraIntent, Constants.MY_OPEN_CARMER);
    }

    private void initView() {

        initTitle();
        initBody();

    }

    @SuppressLint("NewApi")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.MY_OPEN_PHOTO) {
            if (resultCode == Activity.RESULT_OK) {

                commonUri = data.getData();
                String filePath = null;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {// 4.4及以上
                    String wholeID = DocumentsContract.getDocumentId(commonUri);
                    String id = wholeID.split(":")[1];
                    String[] column = {MediaStore.Images.Media.DATA};
                    String sel = MediaStore.Images.Media._ID + "=?";
                    Cursor cursor = getActivity().getContentResolver().query(
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column, sel, new String[]{id}, null);
                    int columnIndex = cursor.getColumnIndex(column[0]);
                    if (cursor.moveToFirst()) {
                        filePath = cursor.getString(columnIndex);
                        commonUri = Uri.parse("file://" + filePath);
                        Log.d("图片", "4.4以上filePath:" + filePath);
                    }
                    cursor.close();
                } else {// 4.4以下，即4.4以上获取路径的方法
                    String[] projection = {MediaStore.Images.Media.DATA};
                    Cursor cursor = getActivity().getContentResolver().query(commonUri, projection, null, null, null);
                    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    cursor.moveToFirst();
                    filePath = cursor.getString(column_index);
                    Log.d("图片", "4.4以下filePath:" + filePath);
                    commonUri = Uri.parse("file://" + filePath);
                }

                startPhotoZoom(commonUri, 800, 600);

            }
        }
        if (requestCode == Constants.MY_OPEN_CARMER) {
            if (resultCode == Activity.RESULT_OK) {
                startPhotoZoom(commonUri, 800, 600);

            }
        }
        if (requestCode == Constants.MY_OPEN_CROP) {
            if (data != null) {
                Log.d("图片", "onActivityResult   commonUri:" + commonUri);

                Log.d("图片", "commonUri.getPath():" + commonUri.getPath());
                // afterCropUri = Uri.parse("file://" + filePath);
                postFile = new File(commonUri.getPath());
                postImage();
            }
        }
    }

    private void startPhotoZoom(Uri uri, int width, int high) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // crop为true是设置在开启的intent中设置显示的view可以剪裁
        intent.putExtra("crop", "true");

        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", width);
        intent.putExtra("outputY", high);
        intent.putExtra("scale", true);
        // intent.putExtra("return-data", true);
        intent.putExtra("return-data", false);
        // String path = getActivity().getCacheDir().getPath() + "/temp.jpg";
        // File file = new File(path);
        // afterCropUri = Uri.fromFile(file);
        // Log.d("图片", "path:" + path);
        // Log.d("图片", "afterCropUri path:" + afterCropUri.getPath());
        //
        // Log.d("图片", "afterCropUri:" + afterCropUri);
        mTmpFile = FileUtils.createTmpFile(getActivity());
        commonUri = Uri.fromFile(mTmpFile);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, commonUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());

        startActivityForResult(intent, Constants.MY_OPEN_CROP);
    }

    private String handleCameraResult(CircleImageView target) {
        if (mTmpFile != null) {
            File f = new File(commonUri.getPath());
            if (f.exists()) {
                postFile = new File(commonUri.getPath());
                postImage();
                return commonUri.getPath();
            }
        }

        return null;
    }

    private void showPopupWindow(PopupWindow pop2, View parentView, View view) {
        pop2.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        pop2.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        // pop2.setFocusable(true);
        // pop2.setOutsideTouchable(false);
        pop2.setBackgroundDrawable(getResources().getDrawable(R.drawable.pv_bg));
        pop2.setContentView(view);
        // �?有属性设置要在show之前完成
        pop2.showAtLocation(parentView, Gravity.BOTTOM, 0, 0);

    }

    private void showNickPopupWindow(PopupWindow pop2, View parentView, View view) {
        pop2.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        pop2.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        pop2.setFocusable(true);
        pop2.setOutsideTouchable(false);
        pop2.setBackgroundDrawable(getResources().getDrawable(R.drawable.pv_bg));
        pop2.setContentView(view);
        // �?有属性设置要在show之前完成
        // pop2.showAtLocation(parentView,
        // Gravity.CENTER_VERTICAL|Gravity.RIGHT, 0, 0);
        // int[] location = new int[2];
        // parentView.getLocationOnScreen(location);

        // pop2.showAtLocation(parentView, Gravity.NO_GRAVITY, location[0],
        // location[1]-pop2.getHeight());
        // pop2.showAsDropDown(parentView);
        pop2.showAtLocation(parentView, Gravity.CENTER, 0, 0);

    }

    // 上传昵称
    private void postHttp() {
        // 传参
//		RequestParams data = new RequestParams();
//		if (nick_name.getText().toString().equals("")) {
//			Log.d("mylog", "kongkongjonggkog");
//		} else {
//			Log.d("mylog", "!!!!!!!!!!!!!!!!!!!!!!kongkongjonggkog");
//		}
//		data.put("nickname", nick_name.getText().toString());
//		data.put("token", SharedPreferencesTools.getTOKEN(getActivity()));
//		HttpUtils.post(Constants.HTTP_POST_NICKNAME, getActivity(), data, new JsonResponseHandler() {
//			@Override
//			public void onSuccess(JSONObject data) {
//				user_name.setText(nick_name.getText().toString());
//				pop1.dismiss();
//			}
//
//		});
    }

}
